package com.example.quiz.service.impl;

import com.example.quiz.dao.AnswerRecordMapper;
import com.example.quiz.model.AnswerRecord;
import com.example.quiz.service.AnswerRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AnswerRecordServiceImpl implements AnswerRecordService {

    @Autowired
    private AnswerRecordMapper answerRecordMapper;

    @Override
    @Transactional(readOnly = true)
    public List<AnswerRecord> getPagedRecords(int page, int size, Long userId) {
        int offset = (page - 1) * size;
        return answerRecordMapper.selectPagedRecords(offset, size, userId);
    }

    @Override
    @Transactional(readOnly = true)
    public int getTotalCount(Long userId) {
        return answerRecordMapper.selectTotalCount(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public int getCorrectCount(Long userId) {
        return answerRecordMapper.selectCorrectCount(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public double getAccuracy(Long userId) {
        int total = getTotalCount(userId);
        if (total == 0) {
            return 0.0;
        }
        int correct = getCorrectCount(userId);
        return (double) correct / total * 100;
    }

    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getStatistics(Long userId) {
        Map<String, Object> stats = new HashMap<>();

        int total = getTotalCount(userId);
        int correct = getCorrectCount(userId);
        double accuracy = getAccuracy(userId);

        stats.put("totalAnswered", total);
        stats.put("correctCount", correct);
        stats.put("wrongCount", total - correct);
        stats.put("accuracy", String.format("%.1f", accuracy));

        // 获取最近答题记录
        List<AnswerRecord> recentRecords = getPagedRecords(1, 5, userId);
        stats.put("recentRecords", recentRecords);

        return stats;
    }

    // BaseService方法实现
    @Override
    public int add(AnswerRecord entity) {
        return answerRecordMapper.insert(entity);
    }

    @Override
    public int deleteById(Long id) {
        return answerRecordMapper.deleteById(id);
    }

    @Override
    public int update(AnswerRecord entity) {
        return answerRecordMapper.update(entity);
    }

    @Override
    public AnswerRecord getById(Long id) {
        return answerRecordMapper.selectById(id);
    }

    @Override
    public List<AnswerRecord> getAll() {
        return answerRecordMapper.selectAll();
    }
}